package com.ithuangyl.annotation_compiler;

import com.google.auto.service.AutoService;
import com.ithuangyl.annotation.BindPath;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.AbstractProcessor;
import javax.annotation.processing.Filer;
import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.Processor;
import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.Element;
import javax.lang.model.element.Name;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;

@AutoService(Processor.class)//注册注解处理器
public class AnnotationCompiler extends AbstractProcessor {

    //生成文件的对象
    Filer filer;

    @Override
    public synchronized void init(ProcessingEnvironment processingEnvironment) {
        super.init(processingEnvironment);
        filer = processingEnvironment.getFiler();
    }

    /**
     * 声明注解处理器支持的java版本
     *
     * @return
     */
    @Override
    public SourceVersion getSupportedSourceVersion() {
        return processingEnv.getSourceVersion();
    }

    /**
     * 声明注解处理器取药处理的注解
     *
     * @return
     */
    @Override
    public Set<String> getSupportedAnnotationTypes() {
        Set<String> types = new HashSet<>();
        types.add(BindPath.class.getCanonicalName());
        return types;
    }


    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        //获取当前模块用到了BindPath的节点
        //TypeElement:类节点
        //ExecutableElement:方法节点
        //VariableElement:成员变量节点
        Set<? extends Element> clementsAnnotatedWith = roundEnv.
                getElementsAnnotatedWith(BindPath.class);

        Map<String, String> activityMap = new HashMap<>();
        Map<String, String> fragmentMap = new HashMap<>();
        for (Element element : clementsAnnotatedWith) {
            TypeElement typeElement = (TypeElement) element;
            BindPath annotation = typeElement.getAnnotation(BindPath.class);
            String key = annotation.value();
            Name className = typeElement.getQualifiedName();
            if (key.contains("activity")){
                activityMap.put(key, className + ".class");
            }else if (key.contains("fragment")){
                fragmentMap.put(key, className + ".class");
            }
        }

        if (activityMap.size() > 0) {
            Writer writer = null;
            String activityName = "ActivityUtil" + System.currentTimeMillis();
            //生成java文件
            try {
                JavaFileObject sourceFile = filer.createSourceFile("com.ithuangyl.util." + activityName);
                writer = sourceFile.openWriter();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("package com.ithuangyl.util;\n\n");
                stringBuilder.append("import com.ithuangyl.aroute.ARouter;\n");
                stringBuilder.append("import com.ithuangyl.aroute.IRouter;\n\n");
                stringBuilder.append("public class "+activityName+" implements IRouter {\n" +
                        "    @Override\n" +
                        "    public void putActivity() {\n");
                Iterator<String> iterator = activityMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String className = activityMap.get(key);
                    stringBuilder.append("        ARouter.create().addActivity(\"" + key + "\", " + className + ");\n");
                }
                stringBuilder.append("    }\n" +
                        "}");
                writer.write(stringBuilder.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }


        if (fragmentMap.size() > 0) {
            Writer writer = null;
            String fragmentName = "FragmentUtil" + System.currentTimeMillis();
            //生成java文件
            try {
                JavaFileObject sourceFile = filer.createSourceFile("com.ithuangyl.util." + fragmentName);
                writer = sourceFile.openWriter();
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append("package com.ithuangyl.util;\n\n");
                stringBuilder.append("import com.ithuangyl.aroute.ARouter;\n");
                stringBuilder.append("import com.ithuangyl.aroute.IFragmentRouter;\n\n");
                stringBuilder.append("public class "+fragmentName+" implements IFragmentRouter {\n" +
                        "    @Override\n" +
                        "    public void putFragment() {\n");
                Iterator<String> iterator = fragmentMap.keySet().iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String className = fragmentMap.get(key);
                    stringBuilder.append("        ARouter.create().addFragment(\"" + key + "\", " + className + ");\n");
                }
                stringBuilder.append("    }\n" +
                        "}");
                writer.write(stringBuilder.toString());
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (writer != null) {
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return false;
    }
}
